package com.aaa.controller;

import cn.hutool.json.JSONUtil;
import com.aaa.entity.TestUser;
import com.aaa.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 测试websocket
 */


@Slf4j
@Component
@ServerEndpoint("/websocketTest001/{sid}")
public class TestController {


    public static ConcurrentHashMap<String, Session> sessionMap = new ConcurrentHashMap<>();

    public static ConcurrentHashMap<String, Result<Object>> objMap = new ConcurrentHashMap<>();

    public static Session sessionInstance ;

    public TestController() {

    }

    @OnOpen
    public void onOpen(Session session, @PathParam("sid") String sid) {
        log.info("打开测试websocket的链接:{}<---->{}",session,sid);
        sessionMap.put(session.getId(),session);
        sessionInstance = session;

    }


    @OnMessage
    public void onMessage(String message) {

        log.info("测试websocket:{}",message);

        TestUser testUser = new TestUser();
        testUser.setUsername(message);
        testUser.setPassword("123456");
        String jsonStr = JSONUtil.toJsonStr(Result.success(testUser));
        sessionMap.forEach((k,v)-> {
            if (!v.isOpen()){
                sessionMap.remove(k,v);
            }
        });
        sessionMap.forEach( (k,v)->{v.getAsyncRemote().sendText(jsonStr);});
    }


    @OnClose
    public void onClose(Session session, @PathParam("sid") String sid) {

        log.info("关闭websocket的链接:{}<---->{}",session,sid);
    }


    @OnError
    public void onError(Session session, @PathParam("sid") String sid, Throwable throwable) {

        log.error("websocket错误:{}<---->{}",session,sid);
        log.error("websocket错误",throwable);

    }

}
